<template>
  <div>
    <basic-container>
      <el-form ref="tableOptionSearch"
               :model="tableOptionSearch"
               label-width="80px"
               size="mini">
        <el-col :span="5">
          <el-form-item label="报停类型:">
            <el-select v-model="tableOptionSearch.state" placeholder="请选择">
              <el-option label="全部" value="-1"></el-option>
              <el-option v-for="(item) in DIC.TROULBE_STATUS" :key="item.id" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="设备类别:">
            <el-cascader v-model="tableOptionSearch.equipmentTypeId"
                         :options="equipmentType"
                         :props="{ expandTrigger: 'hover' }"
                         @change="equipmentTypeChange()"></el-cascader>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="放置位置:">
            <el-select v-model="tableOptionSearch.location" placeholder="请选择">
              <el-option label="全部" value="-1"></el-option>
              <el-option v-for="(item) in DIC.STORAGE_LOCATION" :key="item.id" :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="设备编码:">
            <el-input v-model="tableOptionSearch.coded"
                      placeholder="请输入设备编码"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="设备名称:">
            <el-input v-model="tableOptionSearch.name"
                      placeholder="请输入设备名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="5">
          <el-form-item label="设备型号:">
            <el-input v-model="tableOptionSearch.marking"
                      placeholder="请输入设备型号"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label-width="20px">
            <el-button type="primary"
                       @click="searchFormSubmit()">搜索</el-button>
            <el-button @click="resetSubmit()">重置</el-button>
          </el-form-item>
        </el-col>
      </el-form>
      <avue-crud :option="tableOption"
                 :data="gridData"
                 :table-loading="tableLoading"
                 :page="page" @size-change='sizeChange'
                 @current-change="currentPage"
                 ref="crud">
        <template slot-scope="scope"
                  slot="applyuser">
          {{scope.row.name}}<span>-</span>{{scope.row.state}}
        </template>
        <template slot-scope="scope"
                  slot="menu">
          <el-button type="primary"
                     size="small"
                     plain
                     @click.stop="updModeBtn(scope.row,scope.index)">修改</el-button>
          <el-button type="primary"
                     size="small"
                     plain
                     @click.stop="tableOptionDelBtn(scope.row,scope.index)">删除</el-button>
          <el-button type="primary"
                     size="small"
                     plain
                     @click.stop="wbSubmitBtn(scope.row,scope.index)">维保申请</el-button>
          <el-button type="primary"
                     size="small"
                     plain
                     @click.stop="bfSubmitBtn(scope.row,scope.index)">报废申请</el-button>
        </template>
      </avue-crud>
    </basic-container>

    <el-dialog :title="addFormSelecttitel+'单'" :visible.sync="addMode"  width="40%" center>
      <el-row>
        <el-col :span="5">设备类别：</el-col>
        <el-col :span="6">{{addModeData.equipmentTypeName}}</el-col>
        <el-col :span="5">设别编码：</el-col>
        <el-col :span="6">{{addModeData.coded}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="5">设备名称：</el-col>
        <el-col :span="6">{{addModeData.name}}</el-col>
        <el-col :span="5">型号：</el-col>
        <el-col :span="6">{{addModeData.marking}}</el-col>
      </el-row>
      <el-row>
        <el-col :span="5">品牌：</el-col>
        <el-col :span="6">{{addModeData.brand}}</el-col>
        <el-col :span="5">存放位置：</el-col>
        <el-col :span="6">{{addModeData.locationName}}</el-col>
      </el-row>
      <el-row v-if="examineModeType == 3">
        <el-col :span="5">购买价格：</el-col>
        <el-col :span="6">{{addModeData.price}}</el-col>
        <el-col :span="5">首次启用时间：</el-col>
        <el-col :span="6">{{addModeData.firstOpenTime}}</el-col>
      </el-row>
      <el-row v-if="examineModeType == 3">
        <el-col :span="24">历史维保次数：{{addModeData.historyCount}}  次 （
          保养 {{addModeData.maintainCount}}次，
          效准 {{addModeData.correctCount}}次，
          维修 {{addModeData.maintenanceCount}}次）</el-col>
      </el-row>
      <el-row  v-if="examineModeType == 3">
        <el-col :span="24">历史维保总费用：{{addModeData.historyMoney}}3800 元（
          保养 {{addModeData.maintainMoney}} 元 ，
          效准：{{addModeData.correctMoney}} 元 ，
          维修 {{addModeData.maintenanceMoney}} 元 ）</el-col>
      </el-row>
      <div class="el-divider"></div>
      <el-form :rules="addFormRules" :model="addForm" class="demo-form-inline" size="mini" label-width="100px" ref="addForm">
        <el-col :span="11" >
          <el-form-item :label="addFormSelecttitel+'类型:'" prop="troubleStatus">
            <el-select  v-model="addForm.troubleStatus">
              <el-option v-for="(item) in addFormSelect" :key="item.id"
                         :label="item.label" :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="24" >
          <el-form-item  :label="addFormSelecttitel+'说明:'" prop="troubleNote">
            <el-input type="textarea"
                      placeholder="请输入报废说明"
                      :autosize="{ minRows: 2, maxRows: 4}"
                      v-model="addForm.troubleNote"></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="24">
          <el-form-item>
            <el-button @click="addFormSubmitClose()">关闭</el-button>
            <el-button type="primary"
                       @click="addFormSubmit()">确认</el-button>
          </el-form-item>
        </el-col>

        <el-form-item class="zindex1">
        </el-form-item>
      </el-form>
    </el-dialog>

  </div>
</template>


<script>
import eleCalendar from 'ele-calendar'
import 'ele-calendar/dist/vue-calendar.css'
import { option, optionAdd, optionSelect, optionSelectForm,tableOptionModeSelectRLDateFormRules, tableOptionModeAddFormRules} from "@/const-personal/equipment/aintenance/failure-reporting.js"
import { deepClone } from "@/util/util.js"
import { validatenull } from '@/util/validate'
import { DIC } from '@/const/dic.js'
import { getTroubleList,deleteTroubleID,getTroubleID,updateTroubleID,} from '@/api/equipment/aintenance/failure-reporting.js'
import { getEquipmentType } from '@/api/equipment/device/management.js'
import { DepartmentTreeVChildrenNull,getDepartmentTreeOfId } from "@/util/util.js"
import { addMaintenanceAppointment ,addScrapApplication } from '@/api/equipment/device/management.js'
export default {
  data () {
    return {
      addFormSelecttitel:'',
      addFormSelect:[],
      equipmentType:[],
      DIC :DIC,
      addMode: false,
      addForm: {},
      //添加预约选择区间mode
      tableOptionModeSelectRLDate: false,
      //添加预约选择区间表单
      tableOptionModeSelectRLDateForm: {
        beginDate: '',
        beginTime: '',
        endDate: '',
        endTime: '',
      },
      //流程
      processMode: false,
      //流程数据
      reverse: true,
      activities: [{
        content: '活动按期开始',
        timestamp: '2018-04-15'
      }, {
        content: '通过审核',
        timestamp: '2018-04-13'
      }, {
        content: '创建成功',
        timestamp: '2018-04-11'
      }],
      //添加预约单数据
      tableOptionModeAddForm: {
        remarks: ''
      },
      //添加预约单表单验证
      tableOptionModeAddFormRules: tableOptionModeAddFormRules,
      //添加预约选择区间表单验证
      tableOptionModeSelectRLDateFormRules: tableOptionModeSelectRLDateFormRules,
      //日历插件
      datedef: [
        { 'date': "2019-10-14", 'content': '已预约', "cid": 0 }
      ],
      //日历插件
      prop: 'date', //对应日期字段名,
      updataMode: {
        name: ''
      },
      //预约申请查询
      tableOptionSearch: {
        state: '-1',
        name: "",
        equipmentTypeId:['-1'],
        location: '-1'
      },
      addModeData:{},
      tableOptionModeSelectRL: false, //添加设备选择日历
      tableOption: option, //表格设置属性
      tableOptionAdd: optionAdd,
      tableOptionSelect: optionSelect,
      formOptionSelect: optionSelect,
      tableData: [], //表格的数据
      tablePage: 1,
      tableLoading: false,
      tabelObj: {},
      page: {
        total: 0, //总页数
        currentPage: 1, //当前页数
        pageSize: 10, //每页显示多少条
        pageSizes: [5,10,20] //每页显示多少条
      },
      grade: {
        box: false,
        check: []
      },
      gridData: [],
      treeData: [],
      tableOptionModeAdd: false,
      tableOptionModeSelect: false,
      selectionList: [],
      tableOptionModeSelectFrom: {},
      examineMode: false,
      examineModeType: 0,
      addFormRules:{
          troubleNote: [{ required: true, message: "报废说明不能为空", trigger: "blur" }],
          troubleStatus: [{ required: true, message: "请选择报废类型", trigger: "change" }]

      },
    }
  },
  components: {
    eleCalendar
  },
  created(){
      this.getComEqType()
  },
  methods: {
      currentPage (val) {
          this.page.currentPage = val;
          this.searchFormSubmit();
      },
      sizeChange (val) {
          this.page.pageSize = val
          this.searchFormSubmit()
      },
      resetSubmit(){
          this.tableOptionSearch = {
              state: '-1',
              name: "",
              equipmentTypeId:['-1'],
              location: '-1'
          }
      },
      searchFormSubmit(){
          let data = {
              state: this.tableOptionSearch.state == '-1' ? null : this.tableOptionSearch.state,
              location: this.tableOptionSearch.location == '-1' ? null : this.tableOptionSearch.location,
              equipmentTypeId: this.tableOptionSearch.equipmentTypeId[length] == '-1' ? null : this.tableOptionSearch.equipmentTypeId[length],
              coded: this.tableOptionSearch.coded,
              name: this.tableOptionSearch.name,
              page: this.page.currentPage,
              size: this.page.pageSize,
          }
          this.tableLoading = true
          getTroubleList(data).then(res =>{
            let that = this;
              if(res.data.code==200){
                  that.gridData = [];
                  res.data.data.list.forEach(item=>{
                      let data = item ;
                      // data.equipmentTypeId = getDepartmentTreeOfId(that.equipmentType,item.equipmentTypeId).label;
                      data.equipmentTypeId = getDepartmentTreeOfId(that.equipmentType,item.equipmentId).label;
                      data.troubleStatus = ''+ item.troubleStatus;
                      data.location = '' + item.location;
                      that.gridData.push(data)
                  })
                  that.page.total = res.data.data.total;
                  that.page.currentPage = res.data.data.pageNum;
                  that.page.pageSize = res.data.data.pageSize;
                  that.tableLoading = false
              } else {
                  that.$notify.error({ title: '查询失败', message: '获取数据失败！', type: 'danger', });
              }
          })
      },
    getComEqType () { // 设备类别
        getEquipmentType().then(res => {
            if (res.data.code === 200) {
                this.equipmentType = DepartmentTreeVChildrenNull(res.data.data,[{label:'全部',value:'-1'}])
                this.searchFormSubmit();
            } else {
                this.$notify.error({ title: '查询失败', message: res.data.message, type: 'danger', });
            }
        })
    },
    selectionChange (list) {
      this.selectionList = list
    },
    wbSubmitBtn (row, index) {
      this.examineModeType = 2;
      this.addFormSelect  = DIC.TROULBE_STATUS_WB
      this.getFindByIdFun(row.id)
      this.addFormSelecttitel ='维保'
    },
    bfSubmitBtn (row, index) {
      this.examineModeType = 3;
      this.addFormSelect  = DIC.TROULBE_STATUS_BF
      this.getFindByIdFun(row.id)
      this.addFormSelecttitel ='报废'
    },
    updModeBtn (row, index) {
      this.examineModeType = 1;
      this.addFormSelect  = DIC.TROULBE_STATUS
      this.getFindByIdFun(row.id)
      this.addFormSelecttitel = '报停'
    },
    addFormSubmit(){
        this.$refs.addForm.validate((valid)=>{
            if(valid){
                if( this.examineModeType == 1) {
                    let data = {
                        equipmentId:this.addForm.equipmentId,
                        troubleNote:this.addForm.troubleNote,
                        troubleStatus:this.addForm.troubleStatus,
                        id : this.addForm.id
                    }
                    updateTroubleID(data).then(res => {
                        if (res.data.code === 200) {
                            this.$notify({title: '操作成功', type: 'success', message: '修改成功!'});
                            this.searchFormSubmit();
                            this.addMode = false
                        } else {
                            this.$notify.error({title: '操作失败', message: res.data.message, type: 'danger',});
                        }
                    })
                } else if( this.examineModeType == 2){
                    let data = {
                        equipmentId:this.addForm.equipmentId,
                        remakes:this.addForm.troubleNote,
                        maintenanceType:this.addForm.troubleStatus,
                    }
                    addMaintenanceAppointment(data).then(res => {
                        if (res.data.code === 200) {
                            this.$notify({ title: '操作成功', type: 'success', message: '修改成功!'});
                            this.searchFormSubmit();
                            this.addMode = false
                        } else {
                            this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
                        }
                    })
                } else if( this.examineModeType == 3){
                    let data = {
                        equipmentId:this.addForm.equipmentId,
                        scrapType:this.addForm.troubleNote,
                        maintenanceInstructions:this.addForm.troubleStatus,
                    }
                    addScrapApplication(data).then(res => {
                        if (res.data.code === 200) {
                            this.$notify({title: '操作成功', type: 'success', message: '修改成功!'});
                            this.searchFormSubmit();
                            this.addMode = false
                        } else {
                            this.$notify.error({title: '操作失败', message: res.data.message, type: 'danger',});
                        }
                    })
                }
            }
        })
    },
    getFindByIdFun(id){
        getTroubleID({id:id}).then(res =>{
            if(res.data.code==200){
                this.addModeData = res.data.data
                this.addModeData.equipmentTypeName = getDepartmentTreeOfId(this.equipmentType,res.data.data.equipment.equipmentTypeId).label;
                this.addMode = true
                this.addForm.id = id
                this.addForm = res.data.data

                this.addForm.troubleStatus = ("" + res.data.data.troubleStatus).toString();
                if(this.examineModeType!=1){
                    this.addForm.troubleNote = null
                    this.addForm.troubleStatus = null
                }
            } else {
                this.$notify.error({ title: '操作失败', message: res.data.message, type: 'danger', });
            }
        })
    },
    tableOptionDelBtn (row, index) {
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        //请求--删除
        deleteTroubleID({id:row.id}).then(res=>{
            if(res.data.code==200) {
                this.$notify({ title: '操作成功', type: 'success',message:'删除成功' });
                this.searchFormSubmit()
            } else {
                this.$notify.error({ title: '操作失败', message:res.data.data, type: 'danger', });
            }
        })
      });
    },
    tableOptionAddDel () {
      if (validatenull(this.selectionList)) {
        this.$notify.error({ title: '操作失败', message: '请选择至少一条数据！', type: 'danger', });
        return;
      }
      this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning'
      }).then(() => {
        //请求--删除
        this.selectionList.forEach(item => {
          this.$delete(this.gridData, item.$index)
          this.$refs.crud.toggleSelection(item.$index)
        })
        this.$notify({ title: '删除成功', type: 'success', });
      });
    },
    formhandleEmpty () {
      this.$refs.form.resetForm();
    },
    formhandleSubmit () {
      this.$refs.form.validate(vaild => {
        if (vaild) {
          this.$message.success(JSON.stringify(this.obj0));
        }
      })
    },
    tableOptionModeSelectRLBtn (row, index) {
      this.tableOptionModeSelectRL = true;
    },
    renderContent (h, parmas) {
      const loop = data => {
        return data.defvalue.value ? h('div', [
          h('span', { style: { marginRight: '30px' }, }, data.defvalue.Lunar.lDayChinese),
          h('span', data.defvalue.text),
          h('div', [
            h('span', {
              props: { style: 'lunarcalendarValue' },
              on: {
                click: () => { this.dialogTableVisible = true; }
              }
            }, data.defvalue.value.content),
            h('span', {
              props: { style: 'lunarcalendarValue' },
              on: {
                click: () => { this.dialogTableVisible = true; }
              },
              style: {
                marginLeft: '2px'
              }
            }, data.defvalue.value.content)
          ])
        ]) :
          h('div', [
            h('span', { style: { marginRight: '30px' }, }, data.defvalue.Lunar.lDayChinese),
            h('span', data.defvalue.text)
          ]);
      }
      return (
        <div class='lunarcalendarClass'>
          {loop(parmas)}
        </div>
      );
    },
    datePick (date, event, row, dome) {
      console.log(date);
      console.log(event);
      console.log(row);
      console.log(dome);
      //判断该日期是否能被打开
      this.tableOptionModeSelectRLDate = true;
    },
    tableOptionModeSelectRLDateFormBtn () {
      this.$refs['tableOptionModeSelectRLDateForm'].validate((valid) => {
        if (valid) {
          alert('submit!');
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    processBtn (row) {
      console.log(row)
      this.processMode = true
    },
    addFormSubmitClose(){
          this.addMode = false
    }
  }
}
</script>
<style lang="scss" scoped>
.el-row {
  margin-left: 20px !important;
  margin-bottom: 20px;
  .el-col-3 {
    font-weight: 600;
  }
}
.lineDiv {
  border-top: 1px solid #d6d6d6;
  margin: 0px 1% 20px 25px;
  width: 90%;
}
.el-dialog__body {
  padding-top: 15px;
  padding-bottom: 0px;
}
</style>
<style lang="scss">
.avue-crud__menu {
  min-height: 0px !important;
  margin-bottom: 0px !important;
}
.lunarcalendarClass {
  min-height: 70px;
}
.lunarcalendarClass > div > div > span {
  border: 1px solid #409eff;
  background-color: #409eff;
  color: #ffffff;
  padding: 2px 13px;
  border-radius: 5px;
}
.zindex1 > .el-form-item__content {
  z-index: -1;
}
.xhRed > div > label {
  color: red;
  width: 100px;
  font-size: 18px;
  padding: 3px 5px 0px 0px;
}
.selectMrgin > .avue-crud__tip {
  margin-top: 0px;
}
</style>
